<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/25
 * Time: 15:22
 */

namespace app\share\model;
use Qiniu\Auth;
use think\Loader;

class File
{
    private $accessKey = "2--uYMTLw_dsVe_3l7vt1osTwJ8mhE8ncRseGinm";
    private $secretKey = "8fvNtuXZHIJOV1VqAeUsGZV6s3Q2l8WnG23ML7tL";
    public function __construct()
    {
        //引入extend里面的类
        Loader::import('Qiniu.autoload');

    }

    /**
     * @param $bucket_name  string  资源存储空间
     * @return string  生成上传Token
     */
    public function upToken($bucket_name)
    {
        $this->auth = new Auth( $this->accessKey,$this->secretKey );
        return $this->auth->uploadToken($bucket_name);
    }

    /**
     * @param $file 文件资源
     * @return fail -2003
     */
    public function verification($file)
    {
        $arr_suffix = ['jpg', 'jpeg', 'png', 'gif', 'xlsx','xls'];
        $img_suffix = strtolower( pathinfo( $file['name'],PATHINFO_EXTENSION ) );
        if( !in_array( $img_suffix, $arr_suffix, true ) )
        {
            returnJson(-2003,'资源格式不合法,仅支持jpg、jpeg、png、gif、xlsx、xls');
        }
        if($file['size'] > 2097152)
        {
            #单位字节
            returnJson(-2003,'资源大小不合法,不能超过2MB');
        }
    }

    /**
     * @param $file 文件资源
     * @return  domain_name  文件访问域名
     *          relative_url 文件相对路径
     *          suffix       文件后缀
     *          size         文件大小
     *          original     文件原始名称
     */
    public function uploadFile($file)
    {
        #定义文件上传保存的目录
        $root_path = ROOT_PATH."public";
        $relative_path = DS."upload".DS.date("Ymd").DS;
        $file_dir = $root_path.$relative_path;
        if(!is_dir($file_dir))
        {
            mkdir($file_dir,0777,true);
        }
        #定义新文件名称
        $new_name = uniqid().time().".".pathinfo($file['name'],PATHINFO_EXTENSION);
        #文件后缀
        $suffix = strtolower( pathinfo( $file['name'],PATHINFO_EXTENSION ) );
        #文件大小计算
        if($file['size']/1024 < 1)
        {
            $size = $file['size']."B";
        }else if($file['size']/1024 < 1024)
        {
            $size = sprintf("%.2f",$file['size']/1024)."KB";
        }else{
            $size = sprintf("%.2f",$file['size']/1024/1024)."MB";
        }
        #文件上传移动
        $moveRs = move_uploaded_file($file['tmp_name'],$file_dir.$new_name);
        if($moveRs){
            $data['domain_name']  =  request()->domain();
            $data['relative_url'] =  str_replace('\\', '/',$relative_path.$new_name);
            $data['suffix']       =  $suffix;
            $data['size']         =  $size;
            $data['original']     =  $file['name'];
            return $data;
        }
    }

}